package xyz.liut.autolaunch;

import android.util.Log;

import java.io.IOException;

/**
 * 命令执行工具
 * <p>
 * Create by liut on 20-10-27
 */
public final class ProcessUtil {


    public static Result exec(String cmd, String... params) {
        try {
            Process process = Runtime.getRuntime().exec(cmd, params);
            process.waitFor();
            Result result = new Result(cmd, process);
            process.destroy();
            return result;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 命令执行结果
     */
    public static class Result {
        private static final String TAG = "Process Result";

        public String cmd;

        public int exitValue;

        public String esText;
        public String isText;


        public Result(String cmd, Process process) throws IOException {
            this.cmd = cmd;
            exitValue = process.exitValue();
            esText = IoUtils.stream2String(process.getErrorStream());
            isText = IoUtils.stream2String(process.getInputStream());
        }

        public void println() {
            Log.d(TAG, toString());
        }

        @Override
        public String toString() {
            return "cmd=" + cmd + ", exit=" + exitValue + ", ErrorStream='" + esText + ", InputStream='" + isText;
        }
    }

}
